import type { UserInfo } from "#/store"
import { getUserInfo } from '@/api/auth/index'
import { TOKEN_KEY } from '@/enums/cacheEnum';
import { resetRouter } from "@/router";
import { getToken, setAuthCache } from '@/utils/auth'
import { removeToken } from "@/utils/token";
import { defineStore } from "pinia"
interface UserState {
  userInfo: UserInfo | null;
  token?: string;
  role: string[];
  sessionTimeout?: boolean;
  lastUpdateTime: number;
  userId: string
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): UserState => ({
    userInfo: null,
    token: '',
    role: ['admin'],
    sessionTimeout: false,
    lastUpdateTime: 0,
    userId: ''
  }),
  getters: {
    getToken(): string {
      return this.token || getToken()
    }
  },
  actions: {
    setToken(info: string | undefined) {
      this.token = info ? info : ''
      setAuthCache(TOKEN_KEY, info)
    },
    /**
     *  @description: login
     */
     async GetUserInfo() {
      try {
        const res: any = await getUserInfo()
        if (+res.code === 200) {
          this.userId = res.data.userId
          return Promise.resolve(res.data)
        } else {
          return Promise.reject(res.message)
        }
      } catch (error) {
        return Promise.reject(error)
      }
    },
    /**
     * @description: logout
     */
    logout() {
      this.userId = ''
      removeToken()
      resetRouter()
    }
  }
})